package com.example.mqttxconsumer.controller;

import com.example.mqttxconsumer.config.MqttxProviderConfig;
import com.example.mqttxconsumer.vo.PumpStatus;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/provider")
public class ProviderController {
    private static final Logger log = LoggerFactory.getLogger(ProviderController.class);
    @Resource
    private MqttxProviderConfig mqttxProviderConfig;

    @RequestMapping("/control")
    public String control(@RequestParam(value = "message")String message){
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            PumpStatus pumpStatus = new PumpStatus();
            pumpStatus.setMsg(message);
            String json = objectMapper.writeValueAsString(pumpStatus);
            mqttxProviderConfig.publish(0, true, "watering/control", json);
            return "send success";
        }catch (Exception e){
            log.error("control fail", e);
            return "send fail";
        }
    }

    @RequestMapping("/enable")
    public String enable(@RequestParam(value = "message")String message){
        ObjectMapper objectMapper = new ObjectMapper();
        try{
            PumpStatus pumpStatus = new PumpStatus();
            pumpStatus.setMsg(message);
            String json = objectMapper.writeValueAsString(pumpStatus);
            mqttxProviderConfig.publish(0, true, "watering/auto_mode", json);
            return "send success";
        } catch (Exception e){
            log.error("enable fail", e);
            return "send fail";
        }
    }


}
